//Given an integer array nums, move all 0's to the end of it while maintaining t
//he relative order of the non-zero elements. 
//
// Note that you must do this in-place without making a copy of the array. 
//
// 
// Example 1: 
// Input: nums = [0,1,0,3,12]
//Output: [1,3,12,0,0]
// Example 2: 
// Input: nums = [0]
//Output: [0]
// 
// 
// Constraints: 
//
// 
// 1 <= nums.length <= 104 
// -231 <= nums[i] <= 231 - 1 
// 
//
// 
//Follow up: Could you minimize the total number of operations done? Related Top
//ics 数组 双指针 
// 👍 1251 👎 0


package leetcode.editor.cn;

//Java：Move Zeroes
class P283MoveZeroes {
    public static void main(String[] args) {
        Solution solution = new P283MoveZeroes().new Solution();
        int[] ints = {4, 2, 4, 0, 0, 3, 0, 5, 1, 0};
        solution.moveZeroes(ints);
        System.out.println(ints);
        // TO TEST
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public void moveZeroes(int[] nums) {
            int len = nums.length;
            int[] newArr = new int[len];
            int index = 0;
            for (int num : nums) {
                if (num != 0) {
                    newArr[index++] = num;
                }
            }
            for (int i = 0; i < len; i++) {
                if (i < index) {
                    nums[i] = newArr[i];
                } else {
                    nums[i] = 0;
                }

            }
        }

        public void moveZeroesS(int[] nums) {
            int len = nums.length;
            for (int i = 0; i < len - 1; i++) {
                int j = i + 1;
                int num = nums[i];
                if (num == 0) {
                    while (j < len && nums[j] == 0) {
                        j++;
                    }
                    if (j == len) {
                        return;
                    }
                    swap(nums, i, j);
                }

            }
        }

        public void swap(int[] arr, int i, int j) {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}